package com.oocl.o2o.merchant.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;

import com.oocl.o2o.merchant.dao.AdvertisementDao;
import com.oocl.o2o.merchant.entity.Advertisement;

@Repository
public class AdvertisementDaoImpl implements AdvertisementDao {
	@PersistenceContext
	private EntityManager em;

	@Override
	public Advertisement add(Advertisement t) {
		try {
			em.persist(t);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return t;
	}

	@Override
	public Advertisement update(Advertisement t) {
		try {
			t = em.merge(t);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return t;
	}

	@Override
	public Advertisement delete(String id) {
		try {
			Advertisement adInDb = em.find(Advertisement.class, id);
			em.remove(adInDb);
			return adInDb;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public Advertisement findById(String id) {
		try {
			Advertisement adInDb = em.find(Advertisement.class, id);
			return adInDb;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public List<Advertisement> findAll() {
		
		try {
			String jhql = "select ad from Advertisement ad";
			TypedQuery<Advertisement> query = em.createQuery(jhql, Advertisement.class);
			return query.getResultList();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
